package chapter4;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ViewDictionary
 */
public class ViewDictionary extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ViewDictionary() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	    response.setContentType("text/html;charset=UTF-8");
	    
	    PrintWriter out = response.getWriter();
	    
	    try {
	        // 获取Content对象
            javax.naming.Context ctx = new javax.naming.InitialContext();
            javax.sql.DataSource ds = (javax.sql.DataSource)ctx.lookup("java:/comp/env/jdbc/webdb");
            
            // 执行SQL
            Connection conn = ds.getConnection();
            PreparedStatement pstm = conn.prepareStatement("select * from t_dictionary");
            ResultSet rs = pstm.executeQuery();
            
            // 展示结果
            StringBuffer buff = new StringBuffer();
            buff.append("<table>");
            buff.append("<tr><td>英文</td><td>中文</td></tr>");
            
            while(rs.next()){
                buff.append("<tr><td>");
                buff.append(rs.getString("english"));
                buff.append("</td><td>");
                buff.append(rs.getString("chinese"));
                buff.append("</td></tr>");
            }
            buff.append("</table>");
            
            out.print(buff);
            
            // 释放连接资源
            pstm.close();
            conn.close();
            
        } catch (NamingException e) {
            e.printStackTrace();
            out.println(e);
        } catch (SQLException e) {
            e.printStackTrace();
            out.println(e);
        } 
	}

}
